package org.argus.common.web.core.snowflake;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/5/19
 */
public class WorkerIdAssigner {

    private final RAtomicLong workerIdIncreater;

    /**
     * 服务实例ID自增key前缀
     */
    public static final String SERVICE_ID_INCREMENT_KEY_PREFIX = "ServiceId:Increment:";

    private final long maxWorkerId;

    public WorkerIdAssigner(String applicationName, RedissonClient redissonClient, int workerIdBitLength) {
        workerIdIncreater = redissonClient.getAtomicLong(SERVICE_ID_INCREMENT_KEY_PREFIX + applicationName);
        maxWorkerId = 1L << workerIdBitLength;
    }

    public long assignWorkerId() {
        long currentWorkerValue = workerIdIncreater.incrementAndGet();
        return currentWorkerValue % maxWorkerId;
    }
}
